package com.changwu.cwbase.util;

import android.app.NotificationManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;

import com.blankj.utilcode.util.ConvertUtils;
import com.changwu.cwbase.R;
import com.changwu.cwbase.bean.entity.ShareSDKState;
import com.changwu.cwbase.interfaces.AppShareListener;
import com.mob.MobSDK;
import com.mob.tools.utils.UIHandler;

import java.util.HashMap;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

import static cn.sharesdk.framework.utils.ShareSDKR.getStringRes;

/**
 * @author Administrator
 * @date 19/9/2016.
 */
public class CustomerShare implements PlatformActionListener, Handler.Callback {
    public static final String SHAREWEIBO = "sina";
    public static final String SHAREQQ = "qq";
    public static final String SHAREQZONE = "qzone";
    public static final String SHAREWEIXIN = "weixin";
    public static final String SHAREWEIXINMOMMENTS = "weixinmomments";
    /**
     * 微信朋友圈
     */
    public static final String WECHATMOMENTS = "WechatMoments";
    public static final String SHARE_PLATFORM = "platform";
    public static final String SHARE_OPER_KEY = "oper_key";
    public static final String SHARE_OPER_COMPLETE = "complete";
    public static final String SHARE_OPER_CANCEL = "cancel";
    public static final String SHARE_OPER_ERROR = "error";

    private static final int MSG_TOAST = 1;
    private static final int MSG_ACTION_CCALLBACK = 2;
    private static final int MSG_CANCEL_NOTIFY = 3;

    private PlatformActionListener callback;
    private Context context;
    private String url;
    private ShareSDKState sds;
    private String type;
    private AppShareListener commonListener;

    public PlatformActionListener getCallback() {
        return callback;
    }

    public void setCallback(PlatformActionListener callback) {
        this.callback = callback;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public ShareSDKState getSds() {
        return sds;
    }

    public void setSds(ShareSDKState sds) {
        this.sds = sds;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public CustomerShare() {
        callback = this;
    }

    public AppShareListener getCommonListener() {
        return commonListener;
    }

    public void setCommonListener(AppShareListener commonListener) {
        this.commonListener = commonListener;
    }

    @Override
    public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 1;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);

        if (null != commonListener) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(SHARE_OPER_KEY, SHARE_OPER_COMPLETE);
            params.put(SHARE_PLATFORM, platform.getName());
            commonListener.callBack(params);
        }
    }

    @Override
    public void onError(Platform platform, int action, Throwable t) {
        t.printStackTrace();

        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 2;
        msg.arg2 = action;
        msg.obj = t;
        UIHandler.sendMessage(msg, this);

        // 分享失败的统计
        ShareSDK.logDemoEvent(4, platform);

        if (null != commonListener) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(SHARE_OPER_KEY, SHARE_OPER_ERROR);
            commonListener.callBack(params);
        }
    }

    @Override
    public void onCancel(Platform platform, int action) {
        Message msg = new Message();
        msg.what = MSG_ACTION_CCALLBACK;
        msg.arg1 = 3;
        msg.arg2 = action;
        msg.obj = platform;
        UIHandler.sendMessage(msg, this);

        // 分享失败的统计
        ShareSDK.logDemoEvent(5, platform);

        if (null != commonListener) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(SHARE_OPER_KEY, SHARE_OPER_CANCEL);
            commonListener.callBack(params);
        }
    }

    /**
     * 分享到指定平台(自定义)
     */
    public void shareUiState() {

        MobSDK.init(context);

        //自定義ui分享
        Platform.ShareParams sp = new Platform.ShareParams();
        // 分享时Notification的图标和文字 2.5.9以后的版本不调用此方法
        // oks.setNotification(R.drawable.ic_launcher,
        // getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        sds.setUrl(url);
        sp.setTitle(sds.getTitle());
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        sp.setTitleUrl(sds.getUrl());
        // text是分享文本，所有平台都需要这个字段
        sp.setText(sds.getContent());
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        Drawable drawable = AppResourceUtil.getDraw(R.drawable.ic_launcher);
        sp.setImageData(ConvertUtils.drawable2Bitmap(drawable));// 确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        sp.setUrl(sds.getUrl());
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        sp.setComment(sds.getComment());
        // site是分享此内容的网站名称，仅在QQ空间使用
        sp.setSite(sds.getAppname());
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        sp.setSiteUrl(sds.getUrl());
        Platform platform = null;
        /*if (type.equals(SHAREWEIBO)) {
            platform = ShareSDK.getPlatform(SinaWeibo.NAME);
        } else if (type.equals(SHAREQQ)) {
            // TODO zjy改动 qq分享图片带不过去的问题
//            sp.setImagePath(sds.getImageurl());
            platform = ShareSDK.getPlatform(QQ.NAME);
        } else if (type.equals(SHAREQZONE)) {
//            sp.setImagePath(sds.getImageurl());
            platform = ShareSDK.getPlatform(QZone.NAME);
        } else*/
            if (type.equals(SHAREWEIXIN)) {
            sp.setShareType(Platform.SHARE_WEBPAGE);
            platform = ShareSDK.getPlatform(Wechat.NAME);
        } else if (type.equals(SHAREWEIXINMOMMENTS)) {
            sp.setShareType(Platform.SHARE_WEBPAGE);
            platform = ShareSDK.getPlatform(WechatMoments.NAME);
        }

        platform.SSOSetting(true);
        platform.setPlatformActionListener(callback);
        // 执行图文分享
        platform.share(sp);
    }


    /**
     * 分享到指定平台(自定义)
     */
    public void shareOnlyext(String textContent) {
        MobSDK.init(context);
        //自定義ui分享
        Platform.ShareParams sp = new Platform.ShareParams();
        // text是分享文本，所有平台都需要这个字段
        sp.setText(textContent);
        sp.setShareType(Platform.SHARE_TEXT);

        Platform platform = null;
        /*if (type.equals(SHAREWEIBO)) {
            platform = ShareSDK.getPlatform(SinaWeibo.NAME);
        } else if (type.equals(SHAREQQ)) {
            platform = ShareSDK.getPlatform(QQ.NAME);
        } else if (type.equals(SHAREQZONE)) {
            platform = ShareSDK.getPlatform(QZone.NAME);
        }
        else*/
            if (type.equals(SHAREWEIXIN)) {
            platform = ShareSDK.getPlatform(Wechat.NAME);
        } else if (type.equals(SHAREWEIXINMOMMENTS)) {
            platform = ShareSDK.getPlatform(WechatMoments.NAME);
        }
        platform.SSOSetting(true);
        platform.setPlatformActionListener(callback);
        platform.share(sp);
    }


    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MSG_TOAST: {
                String text = String.valueOf(msg.obj);
                Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            }
            break;
            case MSG_ACTION_CCALLBACK: {
                switch (msg.arg1) {
                    case 1: {
                        // 成功
                        int resId = getStringRes(context, "ssdk_oks_share_completed");
                        if (resId > 0) {
                            //showNotification(context.getString(resId));
                        }
                    }
                    break;
                    case 2: {
                        // 失败
                        String expName = msg.obj.getClass().getSimpleName();
                        if ("WechatClientNotExistException".equals(expName)
                                || "WechatTimelineNotSupportedException".equals(expName)
                                || "WechatFavoriteNotSupportedException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_wechat_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("GooglePlusClientNotExistException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_google_plus_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("QQClientNotExistException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_qq_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("YixinClientNotExistException".equals(expName)
                                || "YixinTimelineNotSupportedException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_yixin_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("KakaoTalkClientNotExistException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_kakaotalk_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("KakaoStoryClientNotExistException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_kakaostory_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else if ("WhatsAppClientNotExistException".equals(expName)) {
                            int resId = getStringRes(context, "ssdk_whatsapp_client_inavailable");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        } else {
                            int resId = getStringRes(context, "ssdk_oks_share_failed");
                            if (resId > 0) {
                                showNotification(context.getString(resId));
                            }
                        }
                    }
                    break;
                    case 3: {
                        // 取消
                        int resId = getStringRes(context, "ssdk_oks_share_canceled");
                        if (resId > 0) {
                            showNotification(context.getString(resId));
                        }
                    }
                    break;
                    default:
                        break;
                }
            }
            break;
            case MSG_CANCEL_NOTIFY: {
                NotificationManager nm = (NotificationManager) msg.obj;
                if (nm != null) {
                    nm.cancel(msg.arg1);
                }
            }
            break;
            default:
                break;
        }
        return false;
    }

    /**
     * 在状态栏提示分享操作
     *
     * @param text
     */
    private void showNotification(String text) {
        Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
    }
}
